<template>
  <div class="dashboard-container">
    <!-- 顶部数据卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8" v-for="(item, index) in statsData" :key="index">
          <div :class="['stat-card', `stat-card-${index}`]">
            <div class="stat-header">
              <span class="stat-title">{{ item.title }}</span>
            </div>
            
              <div class="stat-value"> {{ item.tag[item.avtiveTab].value }} </div>
              <el-row :gutter="20" class="tags">
                <el-col :span="8" v-for="(tag, tagIndex) in item.tag" :key="tagIndex">
                  <div :class="['refresh-indicator', { 'active': tagIndex === item.avtiveTab }]" @click="changeTab(index, tagIndex)">
                    <span>{{ tag.name }}</span>
                    <div class="pulse-dot"></div>
                  </div>
                </el-col>
              </el-row>
            


          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="chart-card">
            <div class="chart-header">
              <h3>收益</h3>
            </div>
            <div ref="commandstats" class="chart-content" style="height: 360px">
              <!-- 这里放置echarts图表组件 -->

            </div>
          </div>
          <!-- 装机模块已隐藏 -->
        </el-col>
        <el-col :span="8" class="tab-card">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="代理排行" name="first">
              <el-table :data="agentRankingData" style="width: 100%">
                <el-table-column label="排名" width="60">
                  <template #default="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="代理商" width="100" />
                <el-table-column prop="income" label="收益" />
                <el-table-column prop="boxes" label="设备数" />
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup name="Index" lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts'
import type { TabsPaneContext } from 'element-plus'
import { listRanking } from "../api/dashboard/ranking.js";
import { getDeviceStats } from "../api/pcdn/info.js";
import { getMonthlyIncomeList } from "../api/dashboard/income.js";

const statsData = ref([
  { title: '设备状态监控', tag: [{ name: "总设备", value: "0"}, { name: "在线设备", value: "0"}, { name: "离线设备", value: "0"}], avtiveTab: 0  },
  { title: '总收益', tag: [{ name: "累计收益", value: "0"}, { name: "昨日收益", value: "0"}, { name: "本月收益", value: "0"}], avtiveTab: 0 },
  { title: '节点统计', tag: [{ name: "节点总数", value: "0"}, { name: "今日新增", value: "0"}, { name: "本月新增", value: "0"}], avtiveTab: 0 },
])

// 代理商排行榜数据
const agentRankingData = ref([])

// 收益统计数据
const incomeData = ref<Array<{month: number, income: number}>>([])

// 获取收益数据
const fetchIncomeData = async () => {
  try {
    // 获取月度收益数据
    const incomeRes = await getMonthlyIncomeList({});
    incomeData.value = incomeRes.data || [];
    console.log('收益统计数据:', incomeData.value);
    
    // 数据获取完成后初始化图表
    if (incomeData.value.length > 0) {
      initChart();
    }
  } catch (error) {
    console.error('获取收益数据失败:', error);
  }
}

// 获取数据
const fetchData = async () => {
  try {
    // 获取设备统计数据
    const deviceStatsRes = await getDeviceStats();
    const deviceData = deviceStatsRes.data;
    
    console.log('设备统计数据:', deviceData);
    
    // 更新设备状态监控数据
    statsData.value[0].tag[0].value = deviceData.totalDevice || 0;
    statsData.value[0].tag[1].value = deviceData.onlineDevice || 0;
    statsData.value[0].tag[2].value = deviceData.offlineDevice || 0;
    
    // 更新总收益数据 - 按照LargeScreen的数据结构
    statsData.value[1].tag[0].value = deviceData.totalIncome || 0;  // 累计收益
    statsData.value[1].tag[1].value = deviceData.yesterdayIncome || 0;  // 昨日收益
    statsData.value[1].tag[2].value = deviceData.monthIncome || 0;  // 本月收益
    
    // 更新设备数据
    statsData.value[2].tag[0].value = deviceData.totalNode || 0;  // 节点总数
    statsData.value[2].tag[1].value = deviceData.todayAddNode || 0; // 今日新增
    statsData.value[2].tag[2].value = deviceData.monthAddNode || 0; // 本月新增
    
    // 获取代理商排行榜
    const rankingRes = await listRanking();
    agentRankingData.value = rankingRes.data || [];
    console.log('代理商排行榜数据:', agentRankingData.value);
    
    // 获取收益统计数据
    await fetchIncomeData();
    
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

// 装机模块已隐藏
// const devices = ref(null)
// onMounted(() => {
//   fetchData();
//   
//   const chartInstance = echarts.init(devices.value, "macarons");
//   chartInstance.setOption({
//     title : {
//         text: '装机统计',
//     },
//     tooltip : {
//         trigger: 'axis'
//     },
//     legend: {
//         data:['意向','预购','成交']
//     },
//     toolbox: {
//         show : true,
//         feature : {
//             mark : {show: true},
//             dataView : {show: true, readOnly: false},
//             magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
//             restore : {show: true},
//             saveAsImage : {show: true}
//         }
//     },
//     calculable : true,
//     xAxis : [
//         {
//             type : 'category',
//             boundaryGap : false,
//             data : ['周一','周二','周三','周四','周五','周六','周日']
//         }
//     ],
//     yAxis : [
//         {
//             type : 'value'
//         }
//     ],
//     series : [
//         {
//             name:'成交',
//             type:'line',
//             smooth:true,
//             itemStyle: {normal: {areaStyle: {type: 'default'}}},
//             data:[10, 12, 21, 54, 260, 830, 710]
//         },
//         {
//             name:'预购',
//             type:'line',
//             smooth:true,
//             itemStyle: {normal: {areaStyle: {type: 'default'}}},
//             data:[30, 182, 434, 791, 390, 30, 10]
//         },
//         {
//             name:'意向',
//             type:'line',
//             smooth:true,
//             itemStyle: {normal: {areaStyle: {type: 'default'}}},
//             data:[1320, 1132, 601, 234, 120, 90, 20]
//         }
//     ]
//   })
// })

// 收益
const commandstats = ref<HTMLElement | null>(null);
let chartInstance: echarts.EChartsType | null = null;

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  chartInstance = echarts.init(commandstats.value, "macarons");
  
  // 准备图表数据
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
  const incomeValues = new Array(12).fill(0);
  
  // 从API数据中提取收益值
  if (incomeData.value && incomeData.value.length > 0) {
    incomeData.value.forEach(item => {
      if (item.month && item.income !== undefined) {
        incomeValues[item.month - 1] = item.income;
      }
    });
  }
  
  // 找到最大值和最小值
  const maxValue = Math.max(...incomeValues);
  const minValue = Math.min(...incomeValues.filter(v => v > 0));
  const maxIndex = incomeValues.indexOf(maxValue);
  const minIndex = incomeValues.indexOf(minValue);
  
  if (chartInstance) {
    chartInstance.setOption({
      title: {
        text: '收益统计',
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          return `${params[0].name}<br/>收益: ${params[0].value}`;
        }
      },
      legend: {
        data: ['收益']
      },
      toolbox: {
        show: true,
        feature: {
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data: months
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '收益'
        }
      ],
      series: [
        {
          name: '收益',
          type: 'bar',
          data: incomeValues,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          markPoint: {
            data: [
              { name: '年最高', value: maxValue, xAxis: maxIndex, yAxis: maxValue, symbolSize: 18 },
              { name: '年最低', value: minValue, xAxis: minIndex, yAxis: minValue }
            ]
          }
        }
      ]
    });

    window.addEventListener("resize", () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    });
  }
};

onMounted(() => {
  fetchData(); // 确保数据获取函数被调用
  
  // 等待数据加载完成后初始化图表
  setTimeout(() => {
    initChart();
  }, 1000);
});

// 移除watch，改为在数据获取完成后直接初始化图表

const changeTab = (index, tagIndex) => {
  statsData.value[index].avtiveTab = tagIndex;
}

const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
 
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 10px;
  padding: 20px;
  height: 150px;
  position: relative;
  overflow: hidden;

  &.stat-card-0 {
    background: url(/src/assets/index/01.png) no-repeat 94%,
      linear-gradient(120deg, #e0f7ff 0%, #c5e7ff 30%, #a7dbff 60%, #87ceeb 100%);
    background-size: contain;
    box-shadow: -2px 1px 5px rgb(187 187 187 / 45%);
  }

  &.stat-card-1 {
    background: url(/src/assets/index/02.png) no-repeat 94%,
    // linear-gradient(120deg, #dff7f7 30%, #b4fbf2 60%, #79fdec 100%);
    linear-gradient(120deg, #cbf4fb 30%, #a8effb 60%, #79eafd 100%);
    background-size: contain;
    box-shadow: -2px 1px 5px rgb(187 187 187 / 45%);
  }

  &.stat-card-2 {
    background: url(/src/assets/index/03.png) no-repeat 94%,
    linear-gradient(120deg, #e5e5ff 30%, #c1c1ff 60%, #a0a0ff 100%);
    background-size: contain;
    box-shadow: -2px 1px 5px rgb(187 187 187 / 45%);
  }

  .stat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .stat-title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  &.stat-card-0 .stat-title {
    color: #15bbff;
  }
  &.stat-card-1 .stat-title {
    color: #00d2f5;
  }
  &.stat-card-2 .stat-title {
    color: #746bef;
  }
  &.stat-card-0 .stat-value {
    color: #15bbff;
  }
  &.stat-card-1 .stat-value {
    color: #00d2f5;
  }
  &.stat-card-2 .stat-value {
    color: #746bef;
  }

  .stat-value {
    font-size: 36px;
    font-weight: bold;
  }
 .tags{
  width: 70%;
 }
  .refresh-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    font-size: 14px;
    margin-top: 8px;
    border-right: 2px solid rgb(255 255 255 / 41%);

    .pulse-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      animation: pulse 2s infinite;
    }
  }

  .refresh-indicator-error {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #fb8383;
    margin-top: 8px;

    .pulse-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #fb8383;
      animation: pulse 2s infinite;
    }
  }

  &.stat-card-0 .refresh-indicator {
    color: #999;
    .pulse-dot {
      background: #999;
      animation: none;
    }
    &.active {
      color: #15bbff;
      .pulse-dot {
        background: #15bbff;
        animation: pulse 2s infinite;
      }
    } 
  }

  &.stat-card-1 .refresh-indicator {
    color: #999;
    .pulse-dot {
      background: #999;
      animation: none;
    }
    &.active {
      color: #00d2f5;
      .pulse-dot {
        background: #00d2f5;
        animation: pulse 2s infinite;
      }
    }
  }

  &.stat-card-2 .refresh-indicator {
    color: #999;
    .pulse-dot {
      background: #999;
      animation: none;
    }
    &.active {
      color: #746bef;
      .pulse-dot {
        background: #746bef;
        animation: pulse 2s infinite;
      }
    }
  }
  &.stat-card-1 .refresh-indicator-error{
    color: #ffa535;
    .pulse-dot {
      background: #ffa535;
    }
  }
  &.stat-card-2 .refresh-indicator-error{
    color: #e5ca0c;
    .pulse-dot {
      background: #e5ca0c;
    }
  }
}

.tags > div:last-child .refresh-indicator {
  border-right: none;
}

.chart-card {
  background: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;

  .chart-header {
    margin-bottom: 20px;

    h3 {
      color: #000;
      font-size: 18px;
      margin: 0;
      position: relative;
      &::before {
        position: absolute;
        content: '';
        width: 4px;
        height: 16px;
        background: #0ec5ae;
        top: 50%;
        transform: translateY(-53%);
        left: -20px;
      }
    }
  }
}

.tab-card {
  padding: 0 10px;
  .demo-tabs {
    padding: 10px;
    background-color: #fff;
    border-radius: 10px;
  }

}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }

  50% {
    transform: scale(1.2);
    opacity: 1;
  }

  100% {
    transform: scale(1);
    opacity: 0.8;
  }
}

// 添加网格背景
.dashboard-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    radial-gradient(circle at 10% 20%, rgba(0, 180, 255, 0.03) 0%, transparent 15%),
    radial-gradient(circle at 90% 80%, rgba(0, 180, 255, 0.03) 0%, transparent 15%),
    repeating-linear-gradient(to right, rgba(0, 180, 255, 0.02) 0, rgba(0, 180, 255, 0.02) 1px, transparent 1px, transparent 20px),
    repeating-linear-gradient(to bottom, rgba(0, 180, 255, 0.02) 0, rgba(0, 180, 255, 0.02) 1px, transparent 1px, transparent 20px);
  pointer-events: none;
  z-index: -1;
}
</style>
